package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.stereotype.Repository;

import pojo.User;
import util.DBUtils;
import dao.UserDao;
@Repository(value="user")
public class UserDaoImpl implements UserDao{

	public User addUser(User user) {
		String sql = "insert into userList(name, pwd, age) values(?,?,?)";
		PreparedStatement pst = null;
		Connection con = null;
		int m = 0;
		try {
			con = DBUtils.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, user.getName());
			pst.setString(2, user.getPwd());
			pst.setInt(3, user.getAge());
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		finally {
			DBUtils.close(con, pst, null);
		}
		return user;
	}

	public User loadUser(String name) {
		String sql = "select * from userList where name=?";
		PreparedStatement pst = null;
		ResultSet rs = null;
		Connection con = null;

		User c = null;
		try {
			con = DBUtils.createConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, name);
			rs = pst.executeQuery();
			if(rs.next()){
				c = new User();
				c.setName(rs.getString("name"));
				c.setPwd(rs.getString("pwd"));
				c.setAge(rs.getInt("age"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		finally {
			DBUtils.close(con, pst, null);
		}
		return c;
	}

}
